package com.duomi.lang;

import java.util.*;

public class DuomiEngine {

    private final Map<String, Object> injectVars = new HashMap<>();
    private final List<Class<?>> injectClasses = new ArrayList<>();
    private final Map<String, DuomiFunction> injectFunctions = new HashMap<>();

    public void export(String name, Object value) {
        injectVars.put(name, value);
    }

    public void export(Class<?> clz) {
        injectClasses.add(clz);
    }

    public void export(String name, DuomiFunction function) {
        injectFunctions.put(name, function);
    }

    private EvalEngine createEngine() {
        final EvalEngine engine = new EvalEngine(Collections.emptyList());

        final EvalEngine.EnvStack envStack = engine.envStack;
        final EvalEngine.Environment injectEnv = envStack.pushNewEnv();
        injectEnv.putAll(injectVars);
        injectEnv.putAll(injectFunctions);
        for (Class<?> clazz : injectClasses) {
            injectEnv.put(clazz.getSimpleName(), clazz);
        }

        return engine;
    }

    public Object eval(String source) {
        final List<Lexer.Token> tokens = new Lexer(source).getTokens();
        return createEngine().eval(tokens);
    }
}
